<!-- 继承页面模板 -->
{% extends 'layout/layui_base_page.html' %}

<!-- 加载静态文件 -->
{% load static %}

<!-- Title -->
{% block title %}
    登陆账号
{% endblock %}

<!-- CSS --->
{% block css %}
    <style>
        #assignTrainArea .layui-inline {
            width: 250px;
        }
    </style>
{% endblock %}

<!-- Content -->
{% block content %}
    <!-- 01: 面包屑导航 -->
    <span class="layui-breadcrumb">
      <a href="javascript:;">首页</a>
      <a href="javascript:;">用户角色</a>
      <a><b>登陆账号</b></a>
    </span>

    <!-- 02: 查询区域 --->
    <div id="queryArea" style="margin-top: 20px;">
        <form class="layui-form">
            {% csrf_token %}
            <div class="layui-form-item">
                <div class="layui-inline">
                    <label class="layui-form-label" for="q_str"><b>查询条件：</b></label>
                    <div class="layui-input-inline">
                        <input type="text" name="q_str" id="q_str" class="layui-input">
                    </div>
                </div>
                <div class="layui-inline">
                    <button type="button" id="btnQuery" class="layui-btn" style="width: 100px"><i
                            class="fa fa-search"></i>&nbsp;&nbsp;查询
                    </button>
                    <button type="button" id="btnAll" class="layui-btn" style="width: 100px"><i class="fa fa-list"></i>&nbsp;&nbsp;全部
                    </button>
                    <button type="button" id="btnAdd" class="layui-btn" style="width: 100px"><i
                            class="fa fa-plus-circle"></i>&nbsp;&nbsp;添加
                    </button>
                </div>
            </div>
        </form>

    </div>

    <!-- 03：表格区域 -->
    <table class="layui-hide" id="accountTable" lay-filter="accountTable"></table>

    <!-- 04: 表格中的按钮 -->
    <script type="text/html" id="tableButton">
        <a class="layui-btn layui-btn-xs layui-btn-normal" lay-event="chpwd">
            <i class="fa fa-key" aria-label="true"></i>&nbsp;修改密码
        </a>
        <a class="layui-btn layui-btn-xs layui-btn-warm" lay-event="edit">
            <i class="fa fa-edit" aria-label="true"></i>&nbsp;编辑
        </a>
        <a class="layui-btn layui-btn-xs layui-btn-danger" lay-event="del">
            <i class="fa fa-trash" aria-label="true"></i>&nbsp;删除
        </a>
    </script>

    <!-- 内容05： 添加、修改账号弹出层的内容-->
    <div id="layerAccountForm" style="display: none; padding: 20px">
        <form class="layui-form" id="accountForm" lay-filter="accountForm">
            {% csrf_token %}
            <!-- 账号，角色，密码，确认密码，姓名，部门，职位，电话，手机，状态，创建时间，更改时间 -->
            <div class="layui-form-item">
                <div class="layui-inline">
                    <label class="layui-form-label" for="loginid"><b>账号：</b></label>
                    <div class="layui-input-inline">
                        <input type="text" name="loginid" id="loginid" class="layui-input">
                        <span class="error_msg" style="color:red; position: absolute"></span>
                    </div>
                </div>
                <div class="layui-inline">
                    <label class="layui-form-label" for="roles"><b>姓名：</b></label>
                    <div class="layui-input-inline">
                        <input type="text" name="name" id="name" class="layui-input">
                        <span class="error_msg" style="color:red; position: absolute"></span>
                    </div>
                </div>
            </div>
            <div class="layui-form-item">
                <div class="layui-inline" style="width: 625px">
                    <label class="layui-form-label" for="roles"><b>角色：</b></label>
                    <div class="layui-input-block">
                        <div id="roles" class="xm-select-demo"></div>
                    </div>
                </div>

            </div>
            <div class="layui-form-item">
                <div class="layui-inline">
                    <label class="layui-form-label" for="loginpwd"><b>密码：</b></label>
                    <div class="layui-input-inline">
                        <input type="password" name="loginpwd" id="loginpwd" class="layui-input">
                        <span class="error_msg" style="color:red; position: absolute"></span>
                    </div>
                </div>
                <div class="layui-inline">
                    <label class="layui-form-label" for="re_loginpwd"><b>确认密码：</b></label>
                    <div class="layui-input-inline">
                        <input type="password" name="re_loginpwd" id="re_loginpwd" class="layui-input">
                        <span class="error_msg" style="color:red; position: absolute"></span>
                    </div>
                </div>
            </div>
            <div class="layui-form-item">
                <div class="layui-inline">
                    <label class="layui-form-label" for="status"><b>状态：</b></label>
                    <div class="layui-input-inline">
                        <input type="checkbox" name="status" id="status" lay-skin="switch" lay-text="启用|禁用">
                        <span class="error_msg" style="color:red; position: absolute"></span>
                    </div>
                </div>
            </div>
            <div class="layui-form-item">
                <div class="layui-inline">
                    <label class="layui-form-label" for="department"><b>部门：</b></label>
                    <div class="layui-input-inline">
                        <input type="text" name="department" id="department" class="layui-input">
                        <span class="error_msg" style="color:red; position: absolute"></span>
                    </div>
                </div>
                <div class="layui-inline">
                    <label class="layui-form-label" for="position"><b>职位：</b></label>
                    <div class="layui-input-inline">
                        <input type="text" name="position" id="position" class="layui-input">
                        <span class="error_msg" style="color:red; position: absolute"></span>
                    </div>
                </div>
            </div>
            <div class="layui-form-item">
                <div class="layui-inline">
                    <label class="layui-form-label" for="mobile"><b>手机号码：</b></label>
                    <div class="layui-input-inline">
                        <input type="text" name="mobile" id="mobile" class="layui-input">
                        <span class="error_msg" style="color:red; position: absolute"></span>
                    </div>
                </div>
                <div class="layui-inline">
                    <label class="layui-form-label" for="email"><b>邮箱地址：</b></label>
                    <div class="layui-input-inline">
                        <input type="text" name="email" id="email" class="layui-input">
                        <span class="error_msg" style="color:red; position: absolute"></span>
                    </div>
                </div>
            </div>
            <div class="layui-form-item">
                <div class="layui-inline">
                    <label class="layui-form-label" for="create_time"><b>创建时间：</b></label>
                    <div class="layui-input-inline">
                        <input type="text" name="create_time" id="create_time" class="layui-input" readonly
                               style="background-color: #eaeaea;">
                    </div>
                </div>
                <div class="layui-inline">
                    <label class="layui-form-label" for="edit_time"><b>更改时间：</b></label>
                    <div class="layui-input-inline">
                        <input type="text" name="edit_time" id="edit_time" class="layui-input" readonly
                               style="background-color: #eaeaea;">
                    </div>
                </div>
            </div>
            <div class="layui-form-item">
                <div class="layui-inline">
                    <label class="layui-form-label" for="create_time"><b>上次登陆：</b></label>
                    <div class="layui-input-inline">
                        <input type="text" name="last_login" id="last_login" class="layui-input" readonly
                               style="background-color: #eaeaea;">
                    </div>
                </div>

            </div>
        </form>
    </div>

    <!-- 内容06: 修改密码的弹出层的内容 -->
    <div id="layerChPwdForm" style="display: none; padding: 20px">
        <form class="layui-form" id="chPwdForm" lay-filter="chPwdForm">
            {% csrf_token %}
            <!-- 账号，角色，密码，确认密码，姓名，部门，职位，电话，手机，状态，创建时间，更改时间 -->
            <div class="layui-form-item">
                <div class="layui-inline" style="width: 360px">
                    <label class="layui-form-label" for="ch_loginid"><b>账号：</b></label>
                    <div class="layui-input-block">
                        <input type="text" name="ch_loginid" id="ch_loginid" class="layui-input" readonly
                               style="background-color:#eaeaea ">
                        <span class="error_msg" style="color:red; position: absolute"></span>
                    </div>
                </div>
            </div>
            <div class="layui-form-item">
                <div class="layui-inline" style="width: 360px">
                    <label class="layui-form-label" for="ch_name"><b>姓名：</b></label>
                    <div class="layui-input-block">
                        <input type="text" name="ch_name" id="ch_name" class="layui-input" readonly
                               style="background-color:#eaeaea ">
                        <span class="error_msg" style="color:red; position: absolute"></span>
                    </div>
                </div>
            </div>

            <div class="layui-form-item">
                <div class="layui-inline" style="width: 360px">
                    <label class="layui-form-label" for="ch_oldPass"><b>原密码：</b></label>
                    <div class="layui-input-block">
                        <input type="password" name="ch_oldPass" id="ch_oldPass" required class="layui-input">
                        <span class="error_msg" style="color:red; position: absolute"></span>
                    </div>
                </div>
            </div>
            <div class="layui-form-item">
                <div class="layui-inline" style="width: 360px">
                    <label class="layui-form-label" for="ch_newPass"><b>新密码：</b></label>
                    <div class="layui-input-block">
                        <input type="password" name="ch_newPass" id="ch_newPass" required class="layui-input">
                        <span class="error_msg" style="color:red; position: absolute"></span>
                    </div>
                </div>
            </div>
            <div class="layui-form-item">
                <div class="layui-inline" style="width: 360px">
                    <label class="layui-form-label" for="ch_re_newPass"><b>确认密码：</b></label>
                    <div class="layui-input-block">
                        <input type="password" name="ch_re_newPass" id="ch_re_newPass" required class="layui-input">
                        <span class="error_msg" style="color:red; position: absolute"></span>
                    </div>
                </div>
            </div>
        </form>
    </div>

{% endblock %}

<!-- JS -->
{% block js %}
    <script src="{% static 'js/xm-select.js' %}"></script>
    <script>
        // ============定义全局变量 Operation 1-添加 2-编辑
        var Operation = 0;
        // 入口函数
        $(function () {
            // === 页面初始化 ===
            initPage();
            // === 响应按钮的点击事件===
            buttonClick();
            // === 表格的初始化 ===
            initTable();

        });

        // ================ 页面初始化的实现 ==================
        function initPage() {
            layui.use(['element'], function () {
                let element = layui.element;
            })
        }

        // =============== 按钮点击的功能实现 =================
        function buttonClick() {
            // === 查询====
            $('#btnQuery').on('click', function () {
                initTable();
            });
            // === 显示全部 ===
            $('#btnAll').on('click', function () {
                location.reload();
            });
            // ==== 添加账号 ====
            $('#btnAdd').on('click', function () {
                // 修改Operation
                Operation = 1;
                loadAccountLayer("添加账号");
            })
        }

        // ================ 表格初始化的实现 ==================
        function initTable() {
            layui.use(['table', 'form'], function () {
                var table = layui.table;
                let form = layui.form;
                // ==== 渲染表格 =====
                table.render({
                    elem: $('#accountTable')
                    , url: "{% url 'list_account' %}"
                    , method: "post"
                    , where: {
                        q_str: $('#q_str').val(),
                        csrfmiddlewaretoken: "{{ csrf_token }}"
                    }
                    , even: true
                    , cols: [[
                        {type: 'numbers', width: 60, title: '序号', align: 'center', sort: true}
                        , {field: 'loginid', width: 90, title: '账号', align: 'center'}
                        , {field: 'name', title: '姓名', width: 100, align: 'center', sort: true}
                        , {
                            field: 'status', width: 120, title: '状态', align: 'center', sort: true,
                            templet: function (res) {
                                // res-- 渲染的一行数据   res.status --- 这一行的状态值
                                if (res.status) {
                                    return "<input type='checkbox' value='" + res.loginid + "' lay-filter='changeEmpStatus' lay-skin='switch' lay-text='启用|禁用' checked >"
                                } else {
                                    return "<input type='checkbox' value='" + res.loginid + "' lay-filter='changeEmpStatus' lay-skin='switch' lay-text='启用|禁用' >"
                                }
                            }
                        }
                        , {field: 'department', width: 100, title: '部门', align: 'center', sort: true}
                        , {field: 'position', width: 100, title: '职位', align: 'center', sort: true}
                        , {field: 'mobile', width: 160, title: '电话', align: 'center', sort: true}
                        , {field: 'email', title: '邮箱', align: 'center', sort: true}
                        , {field: 'last_login', title: '上次登陆', align: 'center', sort: true}
                        , {field: 'create_time', title: '创建时间', align: 'center', sort: true}
                        , {fixed: 'right', title: "操作", width: 260, align: 'center', toolbar: '#tableButton'}
                    ]]
                    , page: true
                    , limit: 15
                    , limits: [15, 20, 25, 30, 50, 100]
                    , done: function (res, curr, count) {
                        // 设置表头的样式
                        $('thead tr').css({'background-color': '#009688', 'color': 'white'})
                    }
                });

                // ==== 响应表格中按钮的点击事件====
                table.on('tool(accountTable)', function (obj) {
                    // 获取点击行的数据
                    let oneLineData = obj.data;
                    // 判断点击的按钮
                    if (obj.event === 'chpwd') {
                        // 加载修改密码的弹出层
                        loadChPwdLayer(oneLineData)

                    } else if (obj.event === 'edit') {
                        // 修改Operation
                        Operation = 2;
                        // 加载弹出层
                        loadAccountLayer("编辑账号", oneLineData);
                    } else if (obj.event === 'del') {
                        deleteValue(oneLineData);
                    }

                });

                // ===== 表格中表单元素的事件响应 ============
                form.on('switch(changeEmpStatus)', function (obj) {
                    // Ajax请求
                    $.ajax({
                        url: "{% url 'change_account_status' %}"
                        , method: 'post'
                        , data: {
                            loginid: obj.value,
                            status: obj.elem.checked ? 1 : 0,
                            csrfmiddlewaretoken: "{{ csrf_token }}"
                        }
                        , success: function (res) {
                            if (res.status) {
                                layui.layer.msg("账号状态修改成功！");
                                initTable();
                            } else {
                                layui.layer.msg(res.error, {
                                    icon: 2, area: ['400px', '200px'], time: -1, btn: ['关闭']
                                })
                            }
                        }
                    })

                })
            })
        }

        // ================ 删除登陆账号 =====================
        function deleteValue(value) {
            // 准备确认删除的文本 
            let confirmStr = "您确认要删除登陆账号【" + value.loginid + " -- " + value.name + "】信息吗？";
            layui.use(['layer'], function () {
                let layer = layui.layer;

                // confirm窗体
                layer.confirm(confirmStr, {
                    icon: 3, title: '<b style="color:red">删除确认</b>', area: ['500px', '200px'], btn: ['确认', '取消']
                }, function (index) {
                    // Ajax
                    $.ajax({
                        url: "{% url 'del_account' %}"
                        , method: 'post'
                        , data: {
                            loginid: value.loginid,
                            csrfmiddlewaretoken: "{{ csrf_token }}"
                        }
                        , success: function (res) {
                            if (res.status) {
                                layui.layer.msg("账号删除成功！");
                                initTable();
                            } else {
                                layui.layer.msg(res.error, {
                                    icon: 2, area: ['400px', '200px'], time: -1, btn: ['关闭']
                                })
                            }
                        }
                    })
                })

            })
        }

        // ================ 添加和修改账号弹出层 ===============
        function loadAccountLayer(title, value = "") {

            console.log(value);

            layui.use(['layer', 'form'], function () {
                let layer = layui.layer;
                let form = layui.form;

                layer.open({
                    type: 1
                    , area: ['800px', '660px']
                    , title: "<b style='color:navy'>【" + title + "】</b>"
                    , btn: ['确定', '取消']
                    , content: $('#layerAccountForm')

                    // ============ 三个回调函数=============
                    , success: function (index, layero) {
                        // 初始化角色的下拉框
                        let roles_select = xmSelect.render({
                            el: '#roles'
                            , name: 'roles'
                            , tips: "请选择所属的角色"
                            , filterable: true
                            , height: '200px'
                            , data: []

                        });
                        // Ajax请求填充下拉框
                        $.ajax({
                            'url': "{% url 'roles_all_select' %}"
                            , method: 'get'
                            , async: false
                            , success: function (res) {
                                roles_select.update({data: res.data});
                            }
                        });
                        // 判断，如果是编辑填充数据
                        if (Operation === 2) {
                            form.val('accountForm', value);
                            $('#loginid').prop('readonly', true).attr('style', 'background-color:#eaeaea');
                            $('#loginpwd, #re_loginpwd').parent().parent().attr('style', 'display:none');
                            $('#loginpwd, #re_loginpwd').val("");
                            form.render();

                            // 赋值角色
                            roles_select.setValue(value.select_roles);
                        }


                    }
                    , yes: function (index, layero) {

                        // 校验表单数据
                        if (!checkFormCommit()) {
                            return;
                        }
                        // 判断是添加还是修改
                        let commitURL = "{% url 'add_account' %}";
                        if (Operation === 2) {
                            commitURL = "{% url 'edit_account' %}"
                        }
                        // =========== ajax提交到后台========
                        $.ajax({
                            url: commitURL
                            , method: 'post'
                            , data: $('#accountForm').serialize()
                            , success: function (res) {
                                if (res.status) {
                                    layui.layer.msg("操作成功！");
                                    location.reload()
                                } else {
                                    layui.layer.msg(res.error, {
                                        icon: 2, area: ['400px', '200px'], time: -1, btn: ['关闭']
                                    })
                                }
                            }
                        })

                    }
                    , end: function (index, layero) {
                        // 初始化表单
                        $('#loginid').val("").prop('readonly', false).attr('style', 'background-color:#FFF');
                        $('#loginpwd, #re_loginpwd').parent().parent().attr('style', 'display:block');
                        form.val('accountForm', {
                            name: "",
                            department: "",
                            position: "",
                            email: '',
                            mobile: '',
                            last_login: "",
                            create_time: '',
                            edit_time: ''
                        });
                    }
                })
            })
        }

        // ================ 修改密码弹出层 ===============
        function loadChPwdLayer(value) {
            console.log(value);
            layui.use(['layer', 'form'], function () {
                let layer = layui.layer;
                let form = layui.form;

                layer.open({
                    type: 1
                    , area: ['500px', '500px']
                    , title: "<b style='color:navy'>【修改密码】</b>"
                    , btn: ['确定', '取消']
                    , content: $('#layerChPwdForm')

                    // ============ 三个回调函数=============
                    , success: function (index, layero) {
                        // 填充修改的账号和姓名
                        $('#ch_loginid').val(value.loginid);
                        $('#ch_name').val(value.name);
                        // 清除所有错误
                        $('.error_msg').empty();

                    }
                    , yes: function (index, layero) {

                        // 1. 校验输入
                        if (!checkChPWdFormCommit()) {
                            return;
                        }

                        // 2. 提交
                        $.ajax({
                            url: "{% url 'change_account_pwd' %}"
                            , method: 'post'
                            , data: $('#chPwdForm').serialize()  // 把表单的数据序列化成字典
                            , success: function (res) {
                                if (res.status) {
                                    // 提示密码修改成功！
                                    layui.layer.msg("密码修改成功！");
                                    // 关闭
                                    layer.close(index);
                                    // 重新舒适化表格
                                    initTable();
                                } else {
                                    layui.layer.msg(res.error, {
                                        icon: 2, area: ['400px', '200px'], time: -1, btn: ['关闭']
                                    })
                                }
                            }
                        })


                    }
                    , end: function (index, layero) {

                    }
                })
            })
        }

        // ========== 实现用户账号表单提交的验证 =============
        function checkFormCommit() {
            // ===== 清除所有的错误 ===
            $('.error_msg').empty();
            // ==== 定义flag变量标识 ===
            let flag = true;

            //1. 学号 ： 4位数字
            let loginid = $('#loginid').val();
            if (loginid.match(/^\d{4}$/) == null) {
                // 修改flag
                flag = false;
                // 展示错误
                $('#loginid').next().text("登陆账号必须要是4位整数！");
            }

            // 2. 密码： A：密码必须大于6位， B：两次密码要一致

            let loginpwd = $('#loginpwd').val();
            let re_loginpwd = $('#re_loginpwd').val();
            if (Operation === 1 && loginpwd.length < 6) {
                // 修改flag
                flag = false;
                // 展示错误
                $('#loginpwd').next().text("密码不能小于6位！");
            }
            if (Operation === 1 && loginpwd != re_loginpwd) {
                // 修改flag
                flag = false;
                // 展示错误
                $('#re_loginpwd').next().text("两次密码不一致！");
            }

            // 3. 姓名: 2-5个汉字
            let name = $('#name').val();
            if (name.match(/^[\u4E00-\u9FA5]{2,5}$/) == null) {
                // 修改flag
                flag = false;
                // 展示错误
                $('#name').next().text("姓名必须是2-5个汉字！");
            }

            // 4. 手机号码
            let mobile = $('#mobile').val();
            if (mobile.match(/^\d{11,12}$/) == null) {
                // 修改result
                flag = false;
                // 展示错误
                $('#mobile').next().text("电话号码必须是11-12的数字！");
            }
            // 5. 邮箱地址
            let email = $('#email').val();
            if (email.match(/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/) == null) {
                // 修改result
                flag = false;
                // 展示错误
                $('#email').next().text("邮箱地址不符合要求！");
            }


            return flag
        }

        // ========== 实现修改密码表单提交的验证 =============
        function checkChPWdFormCommit() {
            // ===== 清除所有的错误 ===
            $('.error_msg').empty();
            // ==== 定义flag变量标识 ===
            let flag = true;

            //1. 旧密码 ： >=6位数字
            let oldPass = $('#ch_oldPass').val();
            if (oldPass.length < 6) {
                // 修改flag
                flag = false;
                // 展示错误
                $('#ch_oldPass').next().text("旧密码不能小于6位！");
            }

            // 2. 第一次输入的新密码： A：密码必须大于6位， B：两次密码要一致

            let new_loginpwd = $('#ch_newPass').val();
            let re_new_loginpwd = $('#ch_re_newPass').val();
            if (new_loginpwd.length < 6) {
                // 修改flag
                flag = false;
                // 展示错误
                $('#ch_newPass').next().text("新密码不能小于6位！");
            }
            if (new_loginpwd != re_new_loginpwd) {
                // 修改flag
                flag = false;
                // 展示错误
                $('#ch_re_newPass').next().text("两次密码不一致！");
            }


            return flag
        }

    </script>

{% endblock %}